package com.tinyseed.hmxx.admin.security.utils;

import com.tinyseed.hmxx.admin.security.domain.JwtUser;
import com.tinyseed.hmxx.common.utils.RSAUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Clock;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.security.PublicKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

@Component
public class JwtTokenUtil implements Serializable {

    private static final long serialVersionUID = -3301605591108950415L;
    private Clock clock = DefaultClock.INSTANCE;

    @Autowired
    private RSAUtils RSAUtils;

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private Long expiration;

    @Value("${jwt.header}")
    private String tokenHeader;

    /*从token 返回用户名*/
    public String getUsernameFromToken(String token) {
        return getClaimFromToken(token, Claims::getSubject);
    }

    private Date getIssuedAtDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getIssuedAt);
    }

    private Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }

    private <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }

    /**
     * Description 解析token，得到token中包含的Claims。
     * Version 1.0
     * Date 2020/2/25 5:10 下午
     * Author howard
     *
     * @param token token字符串
     * @return
     */
    private Claims getAllClaimsFromToken(String token) {
        PublicKey publicKey = RSAUtils.getPublicKey();

        return Jwts.parserBuilder()
                .setSigningKey(publicKey)
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * Description 判断token是否过期
     * Version 1.0
     * Date 2020/2/25 5:11 下午
     * Author howard
     *
     * @param token token字符串
     * @return 返回true 过期，返回false，没过期
     */
    private Boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(clock.now());
    }

    /**
     * Description 判断token是不是在创建密码前面的token
     * Version 1.0
     * Date 2020/2/25 5:12 下午
     * Author howard
     *
     * @param created           创建时间
     * @param lastPasswordReset 最后修改密码的时间
     * @return
     */
    private Boolean isCreatedBeforeLastPasswordReset(Date created, Date lastPasswordReset) {
        return (lastPasswordReset != null && created.before(lastPasswordReset));
    }

    /**
     * Description 判断是否是特殊的token
     * Version 1.0
     * Date 2020/2/25 5:13 下午
     * Author howard
     *
     * @param token
     * @return
     */
    private Boolean ignoreTokenExpiration(String token) {
        // 这里放一些特殊token的，以便针对不同token进行处理
        return false;
    }

    /**
     * Description 生成token，claim申明则map生成
     * Version 1.0
     * Date 2020/2/25 5:13 下午
     * Author howard
     *
     * @param userDetails 传入Userdetails的实现类。
     * @return
     */
    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>();
        return doGenerateToken(claims, userDetails.getUsername());
    }

    /**
     * Description 生成token
     * Version 1.0
     * Date 2020/2/25 5:15 下午
     * Author howard
     *
     * @param claims  token中包含的关键信息
     * @param subject 这个token的主要使用者，subject
     * @return
     */
    private String doGenerateToken(Map<String, Object> claims, String subject) {
        final Date createdDate = clock.now();
        final Date expirationDate = calculateExpirationDate(createdDate);
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(createdDate)
                .setExpiration(expirationDate)
                //使用RSA进行加密
                .signWith(RSAUtils.getPrivateKey(), SignatureAlgorithm.RS256)
                .compact();
    }

    /**
     * Description 判断token是否能刷新，如果token在修改密码之后要求刷新则返回false
     * Version 1.0
     * Date 2020/2/25 5:18 下午
     * Author howard
     *
     * @param token             需要判断的token
     * @param lastPasswordReset 上次更新密码的时间
     * @return 返回true 则token能刷新，返回false，不允许刷新token
     */
    public Boolean canTokenBeRefreshed(String token, Date lastPasswordReset) {
        final Date created = getIssuedAtDateFromToken(token);
        return !isCreatedBeforeLastPasswordReset(created, lastPasswordReset)
                && (!isTokenExpired(token) || ignoreTokenExpiration(token));
    }

    /**
     * Description 更新token
     * Version 1.0
     * Date 2020/2/25 5:17 下午
     * Author howard
     *
     * @param oldToken 旧的token
     * @return
     */
    public String refreshToken(String oldToken) {
        final Date createdDate = clock.now();
        final Date expirationDate = calculateExpirationDate(createdDate);

        final Claims claims = getAllClaimsFromToken(oldToken);
        claims.setIssuedAt(createdDate);
        claims.setExpiration(expirationDate);

        return Jwts.builder()
                .setClaims(claims)
                //设置签名密钥
                .signWith(RSAUtils.getPrivateKey(), SignatureAlgorithm.RS256)
                .compact();
    }

    /**
     * Description 从浏览器http请求头中获取token信息。
     * Version 1.0
     * Date 2020/2/25 5:20 下午
     * Author howard
     *
     * @param request http请求的请求头
     * @return 返回token 字符串
     */
    public String getToken(HttpServletRequest request) {
        final String requestHeader = request.getHeader(tokenHeader);
        return requestHeader;
//        if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
//            return requestHeader.substring(7);
//        }
//        return null;
    }

    /**
     * Description 验证token是否有效
     * Version 1.0
     * Date 2020/2/25 5:22 下午
     * Author howard
     *
     * @param token       浏览器传来的token信息
     * @param userDetails 用户信息
     * @return
     */
    public Boolean validateToken(String token, UserDetails userDetails) {
        JwtUser user = (JwtUser) userDetails;
        final Date created = getIssuedAtDateFromToken(token);
//        final Date expiration = getExpirationDateFromToken(token);
//        如果token存在，且token创建日期 > 最后修改密码的日期 则代表token有效
        return (!isTokenExpired(token)
                && !isCreatedBeforeLastPasswordReset(created, user.getLastPasswordResetDate())
        );
    }

    /**
     * Description 计算token超市时间
     * Version 1.0
     * Date 2020/2/25 5:23 下午
     * Author howard
     *
     * @param createdDate token创建日期
     * @return
     */
    private Date calculateExpirationDate(Date createdDate) {
        return new Date(createdDate.getTime() + expiration);
    }

    /**
     * Description 对secret进行解码
     * Version 1.0
     * Date 2020/2/25 5:24 下午
     * Author howard
     *
     * @return 返回密钥
     */
    @Deprecated
    private SecretKey decodersBase64Secret() {
        return Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret));
    }

}

